from rest_framework.renderers import JSONRenderer
from .constant import CODE_SUCCESS, MSG_SUCCESS, CODE_AUTH_ERROR


class CustomRenderer(JSONRenderer):
    def render(self, data, accepted_media_type=None, renderer_context=None):
        if renderer_context:
            # 响应信息中有message和code这两个key，则获取响应信息中的message和code，并且将原本data中的这两个key删除，放在自定义响应信息里
            # 响应信息中没有则将msg内容改为请求成功 code改为请求的状态码
            status_code = renderer_context["response"].status_code
            if(status_code >= 200 or status_code < 300):
                msg = MSG_SUCCESS
                code = CODE_SUCCESS
            # 如果返回的data为字典
            if isinstance(data, dict):

                try:
                    # 出现detail字段表示出现错误
                    msg = data['detail']
                    code = data['detail'].code
                    if(code == CODE_AUTH_ERROR):
                        renderer_context["response"].status_code = 200

                    data = None
                except Exception:
                    try:
                        msg = data['message']
                        code = data['code']
                    except Exception:
                        pass
                    pass

                try:
                    if data:
                        data = data["data"]
                except Exception:
                    pass

            # 自定义返回的格式
            ret = {
                'code': code,
                'message': msg,
                'data': data,
            }
            return super().render(ret, accepted_media_type=accepted_media_type, renderer_context=renderer_context)
        else:
            return super().render(data, accepted_media_type=accepted_media_type, renderer_context=renderer_context)
